import { defineStore } from 'pinia'
import { ref } from 'vue'
import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr'
import { useMessageStore } from './message'

export const useSignalRStore = defineStore('signalr', () => {
  const connection = ref(null)
  const isConnected = ref(false)
  const isConnecting = ref(false)
  
  // 连接SignalR Hub
  const connect = async (serverUrl, token) => {
    if (isConnected.value || isConnecting.value) {
      return
    }
    
    try {
      isConnecting.value = true
      
      connection.value = new HubConnectionBuilder()
        .withUrl(`${serverUrl}/messageHub`, {
          accessTokenFactory: () => token
        })
        .withAutomaticReconnect([0, 2000, 10000, 30000])
        .configureLogging(LogLevel.Information)
        .build()
      
      // 设置事件监听
      setupEventHandlers()
      
      // 开始连接
      await connection.value.start()
      isConnected.value = true
      console.log('SignalR连接成功')
      
    } catch (error) {
      console.error('SignalR连接失败:', error)
      isConnected.value = false
    } finally {
      isConnecting.value = false
    }
  }
  
  // 断开连接
  const disconnect = async () => {
    if (connection.value) {
      try {
        await connection.value.stop()
        connection.value = null
        isConnected.value = false
        console.log('SignalR连接已断开')
      } catch (error) {
        console.error('断开SignalR连接失败:', error)
      }
    }
  }
  
  // 设置事件监听器
  const setupEventHandlers = () => {
    if (!connection.value) return
    
    const messageStore = useMessageStore()
    
    // 接收消息
    connection.value.on('ReceiveMessage', (message) => {
      console.log('收到新消息:', message)
      messageStore.addMessage(message)
      
      // 显示系统通知
      if (window.electronAPI) {
        window.electronAPI.showNotification({
          title: message.title || '新消息',
          body: message.content || message.summary,
          tag: message.id
        })
      }
    })
    
    // 连接状态变化
    connection.value.onreconnecting(() => {
      console.log('SignalR重连中...')
      isConnected.value = false
    })
    
    connection.value.onreconnected(() => {
      console.log('SignalR重连成功')
      isConnected.value = true
    })
    
    connection.value.onclose(() => {
      console.log('SignalR连接关闭')
      isConnected.value = false
    })
  }
  
  // 发送消息到服务器
  const sendMessage = async (method, ...args) => {
    if (connection.value && isConnected.value) {
      try {
        await connection.value.invoke(method, ...args)
      } catch (error) {
        console.error('发送消息失败:', error)
      }
    }
  }
  
  return {
    connection,
    isConnected,
    isConnecting,
    connect,
    disconnect,
    sendMessage
  }
})